package com.monitor.methods.udpmethod;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.PortUnreachableException;
import java.net.SocketException;
import java.nio.channels.DatagramChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.monitor.methods.TCPMethod;
import com.monitor.methods.UDPMethod;
import com.monitor.persistence.Port;

public class UDPScan implements Runnable {

	private DatagramSocket ds;
	private int start;
	private int stop;
	private InetAddress address;
	private int MAX_TIMEOUT = 3;
	private Map<Integer, Integer> timeoutsMap = new HashMap<Integer, Integer>();
	private List<Port> values;
	
	

	public UDPScan(int start, int stop, InetAddress address, List<Port> values) {
		super();
		this.start = start;
		this.stop = stop;
		this.address = address;
		this.values = values;
	}

	@Override
	public void run() {
		for (int i = start; i < stop; i++) {
			timeoutsMap.put(i, 0);
			Port openPort = scan(i);
			if(openPort != null) {
				values.add(openPort);
			}
//			System.out.println(i);
		}
		UDPMethod.signThreadStopped();
	}
	
	private Port scan(int number) {
		
		DatagramSocket  socket;
	    DatagramPacket  packet;
	    byte[]          message = new byte[256];
	    message = "GET".getBytes();
	    Port port = null;

	    	int sourcePort = 0;
		    	try {
			    	DatagramSocket ds = new DatagramSocket(number);
			    	ds.close();
		    	}
		    	catch (IOException ex) {
		    		System.out.println("Port "+number+" jest zamkniety");
		    	}
	    	
		    //
		    // Send empty request
		    //
//	    	InetSocketAddress addr = new InetSocketAddress(address, number);
//		    socket = new DatagramSocket();
//		    socket.setSoTimeout(2000);
//		    packet = new DatagramPacket(message, message.length,  address, 135);
//		    socket.send(packet);
		    //
		    // Receive reply and print
		    //
//		    packet = new DatagramPacket(message, message.length);
//		    socket.receive(packet);
//		    String received = new String(packet.getData(), 0);
//		    System.out.println("Received: " + received);
//		    socket.close();
//		
//        DatagramPacket dp;
//        DatagramChannel dChannel;
//        Port port = null;
//        DatagramSocket sock;
//        try{
//        	sock = new DatagramSocket();
//        	byte[] buff = new byte[256];
//			DatagramPacket pack = new DatagramPacket(buff, 256, address, number);
//			sock.setSoTimeout(500);
//			boolean received = false;
//			int sendCnt = 0;
//			
//			while(!received && sendCnt < 3)
//			{
//                 //Error refers to the sending of the packet.
//				sock.send(pack);
//				sendCnt++;
//				DatagramPacket packReceive = new DatagramPacket(buff, 256, address, number);
//				try
//				{
//					sock.receive(packReceive);
//					System.err.println(packReceive.getData());
//					received = true;
//					break;
//				}
//				catch(Exception ex)
//				{
//					ex.printStackTrace();
//				}
//			}
//			String str = null;
//			if(received) {
//				System.out.println("Port: "+number+" odebrane");
//				port = new Port(number);
//			}
//             String outMessage = "w ddd";
//             dp = new DatagramPacket(buf, buf.length, address, number);
//             
//             String outString = "Client say: " + outMessage;
//             buf = outString.getBytes();
//             ds = new DatagramSocket();
//             
//             DatagramPacket out = new DatagramPacket(buf, buf.length, address, 9999);
//             ds.send(out);
//
//             ds.receive(dp);
//             String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "
//                 + new String(dp.getData(), 0, dp.getLength());
//             System.out.println(rcvd);
        	
         
//            dp = new DatagramPacket(bytes, bytes.length, address, port);
//            dChannel = DatagramChannel.open();
//            dChannel.connect(new InetSocketAddress(address, port));
//            dChannel.configureBlocking(true);
//            ds = dChannel.socket();
//            ds.setSoTimeout(1000);
//            ds.send(dp);
//            dp = new DatagramPacket(bytes, bytes.length);
//            Thread.sleep(1000);
//            ds.receive(dp);
//
//            //check datagram channel still connected
//            if (!dChannel.isConnected() || !dChannel.isOpen()){
//                ds.close();
//                System.out.println("szalala");
//                return port+"CLOSED";
//            }
//            ds.disconnect();
//            dChannel.disconnect();
//            dChannel.close();
//            ds.close();
//	        return port;
//        }
//        catch(PortUnreachableException e){
//        	e.printStackTrace();
//        	return null;
//        }
//        catch(InterruptedIOException e){
//        	e.printStackTrace();
//        	return null;
//        }
//        catch(IOException e){
//        	e.printStackTrace();
//        	return null;
//        }

	    return null;
	}

}
